using System.Data;
using System.Data.SqlClient;
using Microsoft.Extensions.Configuration;
namespace KL.Standard.Repositories;

/// <summary>
/// 注册的时候 InstancePerLifetimeScope
/// 线程内唯一（也就是单个请求内唯一）
/// </summary>
public class MyDbContext
{
    //private static readonly string connString = ConfigurationManager.ConnectionStrings["Eag_DbConnection_Pro"].ConnectionString;
    private IDbConnection _dbConnection;
    public string dbConnectionstr { set; get; }

    public readonly string ID = System.Guid.NewGuid().ToString();


    public MyDbContext()
    {
        //_log = LogManager.GetLogger(this.GetType());
        //_log.Debug("excute MyDbContext(IConfiguration,string)");
        //this.ID = System.Guid.NewGuid().ToString();

    }

    public IDbConnection DbConnection
    {
        get
        {
            if (_dbConnection == null)
            {
                _dbConnection = new SqlConnection(dbConnectionstr);
                //if (MiniProfiler.Current != null)
                //{
                //    _dbConnection = new StackExchange.Profiling.Data.ProfiledDbConnection((DbConnection)_dbConnection, MiniProfiler.Current);
                //    //https://stackoverflow.com/questions/50581540/dapper-contrib-and-miniprofiler-for-mysql-integration-issues
                //    //SqlMapperExtensions.GetDatabaseType = conn => "MySqlConnection";
                //}
            }

            return _dbConnection;
        }
    }

    /// <summary>
    /// 单数据源的默认获取方式
    /// </summary>
    /// <param name="Configuration"></param>
    public MyDbContext(IConfiguration Configuration)
    {
        //_log.Debug("excute MyDbContext(IConfiguration)");
        //读取配置文件，数据库连接字符串
        //            dbConnectionstr = Configuration.GetValue<string>("Eag_DbConnection_Pro");
    }

    /// <summary>
    /// 通过链接中标签名来获取
    /// </summary>
    /// <param name="connectionTagName">链接标签名字</param>
    public MyDbContext(IConfiguration Configuration, string connectionTagName)
    {
        //_log.Debug("excute MyDbContext(IConfiguration,string)");
        //读取配置文件，数据库连接字符串
        //            dbConnectionstr = Configuration.GetValue<string>("Eag_DbConnection_Pro");
    }

    public MyDbContext(string dbConnectionstr2)
    {
        //_log.Debug("excute MyDbContext(string)");
        //读取配置文件，数据库连接字符串
        //            dbConnectionstr = Configuration.GetValue<string>("Eag_DbConnection_Pro");
    }

    public IDbTransaction DbTransaction { get; set; }

    /// <summary>
    /// 是否已被提交
    /// </summary>
    public bool Committed { get; private set; } = true;

    /// <summary>
    /// 开启事务
    /// </summary>
    public void BeginTransaction()
    {
        Committed = false;
        bool isClosed = DbConnection.State == ConnectionState.Closed;
        if (isClosed) DbConnection.Open();
        DbTransaction = DbConnection?.BeginTransaction();
    }

    /// <summary>
    /// 事务提交
    /// </summary>
    public void CommitTransaction()
    {
        DbTransaction?.Commit();
        Committed = true;

        Dispose();
    }

    /// <summary>
    /// 事务回滚
    /// </summary>
    public void RollBackTransaction()
    {
        DbTransaction?.Rollback();
        Committed = true;

        Dispose();
    }

    /// <summary>
    /// 释放
    /// </summary>
    public void Dispose()
    {
        DbTransaction?.Dispose();
        if (DbConnection.State == ConnectionState.Open)
            _dbConnection?.Close();
    }
}
